package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.Creditor;
import cn.lijinquan.p2p.entites.CreditorSum;
import cn.lijinquan.p2p.entites.ResultMap;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import com.lijinquan.springcloud.utils.*;
import com.lijinquan.springcloud.utils.excelutil.DataFormatUtilInterface;
import com.lijinquan.springcloud.utils.excelutil.ExcelDataFormatException;
import com.lijinquan.springcloud.utils.excelutil.MatchupData;
import com.lijinquan.springcloud.utils.excelutil.SimpleExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 债权录入
 * Created by lijinquan on 2019/10/7.
 */
@RestController
public class CreditorControllerConsumer {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String REST_URL_PREFIX = "http://P2P-ADMIN/";
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/creditor/addCreditor")
    public ResultMap<String> addCreditor(@RequestBody Creditor creditor) {
        ResultMap<String> rm = new ResultMap<>();

        try {

            if (StringUtils.isEmpty(creditor.getContractNo())) { // 判断借款Id（合同编号）是否为空
                rm.setStatus("38");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtorsName())) { // 判断债务人是否为空
                rm.setStatus("39");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtorsId())) { // 判断身份证号是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getLoanPurpose())) { // 判断借款用途是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getLoanType())) { // 判断借款类型是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getLoanPeriod() + "")) { // 判断原始期限（月）是否为空
                rm.setStatus("40");
                return rm;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            if (StringUtils.isEmpty(sdf.format(creditor.getLoanStartDate()))) { // 判断原始借款开始日期是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(sdf.format(creditor.getLoanEndDate()))) { // 判断原始借款到期日期是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getRepaymentStyle() + "")) { // 判断还款方式是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getRepaymenDate())) { // 判断还款日是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getRepaymenMoney() + "")) { // 判断还款金额（元）是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtMoney() + "")) { // 判断债权金额（元）是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtMonthRate() + "")) { // 判断债权年化利率（%）是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtTransferredMoney() + "")) { // 判断债权转入金额是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(sdf.format(creditor.getDebtTransferredDate()))) { // 判断债权转入日期是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getDebtTransferredPeriod() + "")) { // 判断债权转入期限（月）是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(sdf.format(creditor.getDebtRansferOutDate()))) { // 判断债权转出日期是否为空
                rm.setStatus("40");
                return rm;
            }
            if (StringUtils.isEmpty(creditor.getCreditor())) { // 判断债权人是否为空
                rm.setStatus("40");
                return rm;
            }
            //录入债权信息
            creditor.setDebtNo("ZQNO" + RandomNumberUtil.randomNumber(new Date()));//债权id
            creditor.setBorrowerId(1);//贷款人id
            creditor.setDebtStatus(ClaimsType.UNCHECKDE); //债权状态
            creditor.setMatchedMoney(0.00);//匹配金额
            creditor.setMatchedStatus(ClaimsType.UNMATCH); //匹配状态
            creditor.setDebtType(FrontStatusConstants.NULL_SELECT_OUTACCOUNT);//标的类型
            creditor.setAvailablePeriod(creditor.getDebtTransferredPeriod());//可用期限
            creditor.setAvailableMoney(creditor.getDebtTransferredMoney());//可用金额
            Boolean result = restTemplate.postForObject(REST_URL_PREFIX + "/creditor/addCreditor", creditor, Boolean.class);
            rm.setStatus(result ? "1" : "0");

        } catch (Exception e) {
            e.printStackTrace();
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        return rm;

    }

    /**
     * 下载债权批量录入模板
     *
     * @param response
     * @param request
     */
    @RequestMapping("/creditor/download")
    public void downloadCreditorTemp(HttpServletResponse response, HttpServletRequest request) {
        // 得到要下载的文件路径
//        String path = request.getSession().getServletContext()
//                .getRealPath("/WEB-INF/excelTemplate/ClaimsBatchImportTemplate.xlsx");

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "template/ClaimsBatchImportTemplate.xlsx";
        File file = new File(path);
        FileInputStream fis = null;
        try {
            // 1.创建输入流
            fis = new FileInputStream(file);

            // 2.设置响应头
            String filename = DateUtil.getDateStr(new Date(), "yyyyMMddHHmmss") + ".xlsx";
            response.setHeader("content-type", " application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);

            // 3.完成下载
            IOUtils.copy(fis, response.getOutputStream());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @RequestMapping("/creditor/upload")
    public ResultMap<Boolean> uploadCreditorExc(@RequestParam("file") MultipartFile file,
                                                RedirectAttributes redirectAttributes) throws IOException {
        ResultMap<Boolean> rm = new ResultMap<>();

        if (file.isEmpty()) {
            logger.error("message", "Please select a file to upload");
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }


//    // 文件保存路径
//    String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
//            + file.getOriginalFilename();


        // 1.完成文件上传操作
        // 上传文件保存到WEB-INF/upload下
        //String path = this.getRequest().getSession().getServletContext().getRealPath("/WEB-INF/upload");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "upload/";

        //getInputStream() 方法  返回InputStream读取文件的内容

        //getOriginalFilename（）方法是得到原来的文件名在客户机的文件系统名称
        String destName = file.getOriginalFilename();
        // 转存文件
        file.transferTo(new File(path + destName));
        InputStream is = null;
        try {
            // 将文件中内容读取到封装成List<CreditorModel>
            is = new FileInputStream(path + "/" + destName);
            SimpleExcelUtil<Creditor> seu = new SimpleExcelUtil<Creditor>();

            List<Creditor> cms = seu.getDataFromExcle(is, "", 1, new MatchupData<Creditor>() {
                @Override
                public <T> T macthData(List<Object> data, int indexOfRow, DataFormatUtilInterface formatUtil) {
                    Creditor creditor = new Creditor();
                    if (data.get(0) != null) {
                        creditor.setContractNo(data.get(0).toString()); // 债权合同编号
                    } else {
                        throw new ExcelDataFormatException("{" + 0 + "}");
                    }
                    creditor.setDebtorsName(data.get(1).toString().replaceAll("\\s{1,}", " "));// 债务人名称
                    // 身份证号
                    if (data.get(2) != null) {
                        String data2 = data.get(2).toString().replaceAll("\\s{1,}", " ");
                        String[] art = data2.split(" ");
                        for (int i = 0; i < art.length; i++) {
                            String str = art[i];
                            if (!RegValidationUtil.validateIdCard(str)) {
                                throw new ExcelDataFormatException("{" + 2 + "}");
                            }
                        }
                        creditor.setDebtorsId(data2);// 债务人身份证编号
                    } else {
                        throw new ExcelDataFormatException("{" + 2 + "}");
                    }
                    creditor.setLoanPurpose(data.get(3).toString()); // 借款用途
                    creditor.setLoanType(data.get(4).toString());// 借款类型
                    creditor.setLoanPeriod(formatUtil.formatToInt(data.get(5), 5)); // 原始期限月
                    creditor.setLoanStartDate(formatUtil.format(data.get(6), 6));// 原始借款开始日期
                    creditor.setLoanEndDate(formatUtil.format(data.get(7), 7));// 原始贷款到期日期
                    // 还款方式
                    if (ConstantUtil.EqualInstallmentsOfPrincipalAndInterest.equals(data.get(8))) {// 等额本息
                        creditor.setRepaymentStyle(11601);
                    } else if (ConstantUtil.MonthlyInterestAndPrincipalMaturity.equals(data.get(8))) {// 按月付息到月还本
                        creditor.setRepaymentStyle(11602);
                    } else if (ConstantUtil.ExpirationTimeRepayment.equals(data.get(8))) {// 到期一次性还款
                        creditor.setRepaymentStyle(11603);
                    } else {
                        throw new ExcelDataFormatException("在单元格{" + 8 + "}类型不存在");
                    }
                    creditor.setRepaymenDate(data.get(9).toString());// 每月还款日
                    creditor.setRepaymenMoney(formatUtil.formatToDouble(data.get(10), 10));// 月还款金额
                    creditor.setDebtMoney(formatUtil.formatToDouble(data.get(11), 11));// 债权金额
                    creditor.setDebtMonthRate(formatUtil.formatToDouble(data.get(12), 12));// 债权月利率
                    creditor.setDebtTransferredMoney(formatUtil.formatToDouble(data.get(13), 13));// 债权转入金额
                    creditor.setDebtTransferredPeriod(formatUtil.formatToInt(data.get(14), 14));// 债权转入期限
                    creditor.setDebtRansferOutDate(formatUtil.format(data.get(15), 15));// 债权转出日期
                    creditor.setCreditor(data.get(16).toString());// 债权人

                    // 债权转入日期 原始开始日期+期限
                    Date startDate = formatUtil.format(data.get(6), 6); // 原始开始日期
                    int add = formatUtil.formatToInt(data.get(14), 14);// 期限
                    Calendar c = Calendar.getInstance();
                    c.setTime(startDate);
                    c.add(Calendar.MONTH, add);
                    creditor.setDebtTransferredDate(c.getTime());

                    Date da = new Date();
                    creditor.setDebtNo("ZQNO" + RandomNumberUtil.randomNumber(da));// 债权编号
                    creditor.setMatchedMoney(Double.valueOf("0"));// 已匹配金额
                    creditor.setDebtStatus(ClaimsType.UNCHECKDE); // 债权状态
                    creditor.setMatchedStatus(ClaimsType.UNMATCH);// 债权匹配状态
                    creditor.setBorrowerId(1); // 借款人id
                    creditor.setDebtType(FrontStatusConstants.NULL_SELECT_OUTACCOUNT); // 标的类型
                    creditor.setAvailablePeriod(creditor.getDebtTransferredPeriod());// 可用期限
                    creditor.setAvailableMoney(creditor.getDebtTransferredMoney());// 可用金额
                    return (T) creditor;

                }
            });
            // 3.调用service完成批量导入操作

            Boolean res = restTemplate.postForObject(REST_URL_PREFIX + "/creditor/addCreditorBatch", cms, Boolean.class);
            rm.setStatus(res ? "1" : "0");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return rm;
    }

    @RequestMapping("/creditor/getCreditorlist")
    public ResultMap<HashMap<String, Object>> getCreditorlist(HttpServletRequest request) {
        ResultMap<HashMap<String, Object>> rm = new ResultMap<>();
        String dDebtNo = request.getParameter("dDebtNo"); // 债权编号
        String token = request.getParameter("token"); // Token
        String dDebtTransferredDateStart = request.getParameter("dDebtTransferredDateStart"); // 债权转入日期
        String dDebtTransferredDateEnd = request.getParameter("dDebtTransferredDateEnd"); // 债权转入日期
        String dContractNo = request.getParameter("dContractNo"); // 借款Id（合同编号）
        String dDebtStatus = request.getParameter("dDebtStatus"); // 债权状态
        String dMatchedStatus = request.getParameter("dMatchedStatus"); // 债权匹配状态
        String dDebtMonthRateStart = request.getParameter("dDebtMonthRateStart"); // 债权月利率（%）
        String dDebtMonthRateEnd = request.getParameter("dDebtMonthRateEnd"); // 债权月利率（%）
        String offsetnum = request.getParameter("offsetnum"); // 第几页

        try {

            Map<String, Object> mapOrg = new HashMap<String, Object>();
            // 自定义级别的日志 用来记录关键操作到数据库

            if (StringUtils.isEmpty(offsetnum)) { // 判断开始条数
                // logger.debug(offsetnum + "不能为空");
                rm.setStatus(FrontStatusConstants.BREAK_DOWN);
                return rm;
            }
            if (offsetnum != null && !"".equals(offsetnum)) {
                mapOrg.put("offsetnum", Integer.valueOf(offsetnum));
            } else {
                mapOrg.put("offsetnum", null);
            }
            if (dDebtNo != null && !"".equals(dDebtNo)) {
                mapOrg.put("dDebtNo", dDebtNo);
            } else {
                mapOrg.put("dDebtNo", null);
            }
            if (dDebtStatus != null && !"".equals(dDebtStatus)) {
                mapOrg.put("dDebtStatus", Integer.valueOf(dDebtStatus));
            } else {
                mapOrg.put("dDebtStatus", null);
            }
            if (dMatchedStatus != null && !"".equals(dMatchedStatus)) {
                mapOrg.put("dMatchedStatus", Integer.valueOf(dMatchedStatus));
            } else {
                mapOrg.put("dMatchedStatus", null);
            }
            if (dContractNo != null && !"".equals(dContractNo)) {
                mapOrg.put("dContractNo", dContractNo);
            } else {
                mapOrg.put("dContractNo", null);
            }
            if (dDebtMonthRateStart != null && !"".equals(dDebtMonthRateStart)) {
                mapOrg.put("dDebtMonthRateStart", Double.valueOf(dDebtMonthRateStart));
            } else {
                mapOrg.put("dDebtMonthRateStart", null);
            }
            if (dDebtMonthRateEnd != null && !"".equals(dDebtMonthRateEnd)) {
                mapOrg.put("dDebtMonthRateEnd", Double.valueOf(dDebtMonthRateEnd));
            } else {
                mapOrg.put("dDebtMonthRateEnd", null);
            }
            if (dDebtTransferredDateStart != null && !"".equals(dDebtTransferredDateStart)) {
                mapOrg.put("dDebtTransferredDateStart", DateUtil.getStartDate(dDebtTransferredDateStart));
            } else {
                mapOrg.put("dDebtTransferredDateStart", null);
            }
            if (dDebtTransferredDateEnd != null && !"".equals(dDebtTransferredDateEnd)) {
                mapOrg.put("dDebtTransferredDateEnd", DateUtil.getEndDate(dDebtTransferredDateEnd));
            } else {
                mapOrg.put("dDebtTransferredDateEnd", null);
            }

            int limitnum = 20;
            int offsetN = Integer.valueOf(offsetnum);
            offsetN = (offsetN - 1) * limitnum;
            mapOrg.put("offsetN", Integer.valueOf(offsetN));
            mapOrg.put("limitnum", limitnum);
            List<Creditor> data = restTemplate.postForObject(REST_URL_PREFIX + "/creditor/getCreditorPages", mapOrg, List.class);
            if (data == null) {
                rm.setStatus(FrontStatusConstants.BREAK_DOWN);
                return rm;
            }
            //	logger.debug("债权查询结果" + data);
            CreditorSum datasum = restTemplate.postForObject(REST_URL_PREFIX + "/creditor/getCreditorSum", mapOrg, CreditorSum.class);
            if (datasum == null) {
                rm.setStatus(FrontStatusConstants.BREAK_DOWN);
                return rm;
            }
            HashMap<String, Object> datemap = new HashMap<String, Object>();
            datemap.put("date", data);
            datemap.put("datasum", datasum);
            rm.setBody(datemap);
            return rm;
        } catch (Exception e) {
            e.printStackTrace();
            // logger.debug("债权查询时出现问题"+e);
        }
        return rm;

    }

    /**
     * 债权审核
     * @param request
     * @return
     */

    @RequestMapping("/creditor/checkCreditor")
    public ResultMap<Boolean> checkCreditor(HttpServletRequest request) {

        ResultMap<Boolean> rm = new ResultMap<>();

        try {
            String audit_result = request.getParameter("audit_result");// 审核不通过理由
            String audit_flg = request.getParameter("audit_flg"); // 审核不通过为0;审核为1
            String ids = request.getParameter("ids");

            if (StringUtils.isEmpty(ids.toString())) {
                // logger.debug("未选中需要债权审核的数据！");
                rm.setStatus("61");
                return rm;
            }
            String[] debtIds = ids.split(",");
            if (StringUtils.isEmpty(audit_flg)) { // 审核不通过为0;审核为1
                // logger.debug("audit_flg不能为空 " + audit_flg);
                rm.setStatus("62");
                return rm;
            }
            Map<String, Object> mapCreditor = new HashMap<String, Object>();
            mapCreditor.put("checkID", debtIds);
            mapCreditor.put("audit_result", audit_result);
            mapCreditor.put("audit_flg", audit_flg);
            Boolean aBoolean = restTemplate.postForObject(REST_URL_PREFIX + "/creditor/checkCreditor", mapCreditor, Boolean.class);
            // logger.debug("债权审核成功！");
            rm.setBody(aBoolean);
            if (!aBoolean) {
                rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // logger.debug("债权审核出现问题！"+e);
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);

        }
        return rm;
    }

    /**
     * 查看债权详情
     * @param request
     * @return
     */
    @RequestMapping("/creditor/viewCreditDetail")
    public ResultMap<Map<String ,Object>> viewCreditDetail(HttpServletRequest request){

        ResultMap<Map<String ,Object>> rm=new ResultMap<>();

        String dDebtNo = request.getParameter("dDebtNo");
        String token = request.getParameter("token");

        if(StringUtils.isEmpty(dDebtNo)){
            rm.setStatus(FrontStatusConstants.BREAK_DOWN);
            return rm;
        }
        Creditor creditor = restTemplate.getForObject(REST_URL_PREFIX + "/creditor/viewCreditDetail/"+dDebtNo, Creditor.class);
        Map<String ,Object> o=new HashMap<>();
        o.put("dDebtNo",creditor.getDebtNo());//标的编号
        o.put("dContractNo",creditor.getContractNo());//合同编号
        o.put("dDebtorsName",creditor.getDebtorsName());//债务人
        o.put("dDebtorsId",creditor.getDebtorsId());  //身份证号
        o.put("dLoanPurpose",creditor.getLoanPurpose());//借款用途
        o.put("dLoanType",creditor.getLoanType());//借款类型
        o.put("dLoanPeriod",creditor.getLoanPeriod());//原始期限
        o.put("dLoanStartDate",creditor.getLoanStartDate());//原始期限开始日期
        o.put("dLoanEndDate",creditor.getLoanEndDate());//原始期限结束日期
        o.put("dRepaymentStyleName",creditor.getRepaymentStyleName());//还款方式
        o.put("dRepaymenDate",creditor.getRepaymenDate());//还款日
        o.put("dRepaymenMoney",creditor.getRepaymenMoney());//还款金额
        o.put("dDebtMoney",creditor.getDebtMoney());//债权金额 元
        o.put("dDebtMonthRate",creditor.getDebtMonthRate());//债权月利率
        o.put("dDebtTransferredMoney",creditor.getDebtTransferredMoney());//债权转入金额
        o.put("dDebtTransferredPeriod",creditor.getDebtTransferredPeriod());//债权转入期限
        o.put("dDebtTransferredDate",creditor.getDebtTransferredDate());//债权转入日期
        o.put("dDebtRansferOutDate",creditor.getDebtRansferOutDate());//债权转出日期
        o.put("dCreditor",creditor.getCreditor());//债权人
        rm.setBody(o);
        return rm;
    }

}
